package com.example.wyh.intelcheckbash.bug;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.HttpUtil;
import com.example.wyh.intelcheckbash.LocalStorage;
import com.example.wyh.intelcheckbash.R;
import com.example.wyh.intelcheckbash.SettingActivity;
import com.example.wyh.intelcheckbash.StatisticalCheckActivity;
import com.example.wyh.intelcheckbash.common.SysExitUtil;
import com.example.wyh.intelcheckbash.sqlite.TaskDbHelper;
import com.example.wyh.intelcheckbash.task.UploadCheckedTaskActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Time;
import java.util.ArrayList;

/**
 * Created by chen on 17/11/29.
 */

public class BugRecordActivity extends AppCompatActivity {
    public Spinner mMachineGroup;
    public TextView mBugEquipmentCode;
    public EditText mBugEquipmentName;
    public EditText mBugEquipmentSystem;
    public EditText mBugName;
    public TextView mFindTime;
    public Spinner mBugRecordLevel;
    public EditText mBugAppearance;
    public Spinner mFindBugDepart;
    public EditText mFindOwner;
    public TextView mBugFirstLinkName;
    public Spinner mLinkProfession;
    public TextView mLinkTime;
    public EditText mRemark;
    public String mStrLinkDate = "";
    public String mStrFindDate = "";

    public Button confirm_select_find_time_id;
    public Button confirm_select_link_time_id;

    public String mDeviceToken;
    private String mYhxtm;

    public RelativeLayout selectCalendarFindTimeRL;
    public CalendarView selectCalendarFindTime;

    public RelativeLayout selectCalendarLinkTimeRL;
    public CalendarView selectCalendarLinkTime;
    public TimePicker mLinkTimePicker;
    public TimePicker mFindTimePicker;

    public void getHttpHeads() {

        TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        mDeviceToken = TelephonyMgr.getDeviceId();
        JSONObject User = LocalStorage.getObject(BugRecordActivity.this, "User");
        mYhxtm = "";
        try {
            mYhxtm = User.getString("yhxtm");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bug_record);
        SysExitUtil.activityList.add(BugRecordActivity.this);
        getHttpHeads();
        initActionBar();

        JSONObject user = LocalStorage.getObject(BugRecordActivity.this, "User");

        ArrayList machineGroupList = getMachineGroupList();
        mMachineGroup = initSpinner("选择机组",R.id.bug_record_machine_group,machineGroupList);

        mBugEquipmentCode = (TextView)findViewById(R.id.bug_equipment_code);
        mBugEquipmentCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(BugRecordActivity.this,CodeInfoActivity.class),1000);
            }
        });
        mBugEquipmentName = (EditText)findViewById(R.id.bug_equipment_name);
        mBugEquipmentSystem = (EditText)findViewById(R.id.bug_equipment_system);
        mBugName = (EditText)findViewById(R.id.bug_name);
        mFindTime = (TextView)findViewById(R.id.bug_find_time);
        confirm_select_find_time_id = (Button)findViewById(R.id.confirm_select_find_time_id);
        confirm_select_find_time_id.setVisibility(View.GONE);
        confirm_select_find_time_id.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectCalendarFindTimeRL.setVisibility(View.GONE);
                mFindTimePicker.setVisibility(View.GONE);
                confirm_select_find_time_id.setVisibility(View.GONE);
            }
        });
        mFindTime.setText(HttpUtil.getCurrentDateStringOnlyDate());
        mFindTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (selectCalendarFindTimeRL.getVisibility() == View.VISIBLE)
                {
                    selectCalendarFindTimeRL.setVisibility(View.GONE);
                    selectCalendarFindTime.setVisibility(View.GONE);
                    mFindTimePicker.setVisibility(View.GONE);
                    confirm_select_find_time_id.setVisibility(View.GONE);
                }
                else
                {
                    selectCalendarFindTimeRL.setVisibility(View.VISIBLE);
                    selectCalendarFindTime.setVisibility(View.VISIBLE);
                }
            }
        });

        selectCalendarFindTimeRL = (RelativeLayout)findViewById(R.id.selectCalendarFindTimeRL);
        selectCalendarFindTimeRL.setVisibility(View.GONE);
        selectCalendarFindTime = (CalendarView)findViewById(R.id.selectCalendarViewFindTime);
        selectCalendarFindTime.setVisibility(View.GONE);
        selectCalendarFindTime.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView calendarView, int i, int i1, int i2) {
                String month = i1 + 1 < 10 ? "0" + (i1 + 1) : (i1 + 1) + "";
                String day = i2 < 10 ? "0" + i2 : i2 + "";
                String selectDate = i + "-" + month + "-" + day;
                mStrFindDate = selectDate;
                selectCalendarFindTime.setVisibility(View.GONE);
                mFindTimePicker.setVisibility(View.VISIBLE);
                confirm_select_find_time_id.setVisibility(View.VISIBLE);
            }
        });
        mFindTimePicker = (TimePicker)findViewById(R.id.findTimePicker);
        mFindTimePicker.setVisibility(View.GONE);
        mFindTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker timePicker, int i, int i1) {
                String hour = i<10? "0"+i : i+"";
                String minute = i1<10 ? "0"+i1 :i1+"";
                mFindTime.setText(mStrFindDate + " "+ hour+ ":" + minute);
            }
        });

        ArrayList bugLevels = getDefectLevel();
        mBugRecordLevel = initSpinner("选择缺陷等级",R.id.bug_record_bug_level,bugLevels);

        mBugAppearance = (EditText)findViewById(R.id.bug_appearance);

        ArrayList departments = getDepartmentMajorList();
        mFindBugDepart = initSpinner("选择部门",R.id.find_bug_department,departments);
        mFindBugDepart.setSelection(getPreSelectArrayListIndex(departments,getValueByKey(user, "deptname")));

        mFindOwner = (EditText)findViewById(R.id.bug_find_owner);

        mFindOwner.setText(getValueByKey(user, "usernamecn"));
        mBugFirstLinkName = (TextView)findViewById(R.id.bug_first_link_name);
        mBugFirstLinkName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(BugRecordActivity.this,LinkerInfoActivity.class),1001);
            }
        });

        mLinkProfession = initSpinner("选择联系专业",R.id.link_profession,getLinkMajorList());
        mLinkTime = (TextView)findViewById(R.id.link_time);
        mLinkTime.setText(HttpUtil.getCurrentDateStringOnlyDate());
        mLinkTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (selectCalendarLinkTimeRL.getVisibility() == View.VISIBLE)
                {
                    selectCalendarLinkTimeRL.setVisibility(View.GONE);
                    selectCalendarLinkTime.setVisibility(View.GONE);
                    mLinkTimePicker.setVisibility(View.GONE);
                    confirm_select_link_time_id.setVisibility(View.GONE);
                }else
                {
                    selectCalendarLinkTimeRL.setVisibility(View.VISIBLE);
                    selectCalendarLinkTime.setVisibility(View.VISIBLE);
                }

            }
        });

        confirm_select_link_time_id = (Button)findViewById(R.id.confirm_select_link_time_id);
        confirm_select_link_time_id.setVisibility(View.GONE);
        confirm_select_link_time_id.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectCalendarLinkTimeRL.setVisibility(View.GONE);
                mLinkTimePicker.setVisibility(View.GONE);
                confirm_select_link_time_id.setVisibility(View.GONE);
            }
        });

        selectCalendarLinkTimeRL = (RelativeLayout)findViewById(R.id.selectCalendarLinkTimeRL);
        selectCalendarLinkTimeRL.setVisibility(View.GONE);
        selectCalendarLinkTime = (CalendarView)findViewById(R.id.selectCalendarViewLinkTime);
        selectCalendarLinkTime.setVisibility(View.GONE);
        selectCalendarLinkTime.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView calendarView, int i, int i1, int i2) {
                String month = i1 + 1 < 10 ? "0" + (i1 + 1) : (i1 + 1) + "";
                String day = i2 < 10 ? "0" + i2 : i2 + "";
                String selectDate = i + "-" + month + "-" + day;
                selectCalendarLinkTime.setVisibility(View.GONE);
                mLinkTimePicker.setVisibility(View.VISIBLE);
                confirm_select_link_time_id.setVisibility(View.VISIBLE);
                mStrLinkDate = selectDate;
            }
        });
        mLinkTimePicker = (TimePicker)findViewById(R.id.linkTimePicker);
        mLinkTimePicker.setVisibility(View.GONE);
        mLinkTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker timePicker, int i, int i1) {
//                selectCalendarLinkTimeRL.setVisibility(View.GONE);
//                mLinkTimePicker.setVisibility(View.GONE);
                String hour = i<10? "0"+i : i+"";
                String minute = i1<10 ? "0"+i1 :i1+"";
                mLinkTime.setText(mStrLinkDate + " "+ hour+ ":" + minute);
            }
        });

        mRemark = (EditText)findViewById(R.id.remark_text);

        Button upload_bug_btn = (Button)findViewById(R.id.upload_bug_btn);
        upload_bug_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                JSONObject updateBug = new JSONObject();
                try
                {
                    updateBug.put("jz",mMachineGroup.getSelectedItem().toString());
                    updateBug.put("sbbm",mBugEquipmentCode.getText().toString());
                    updateBug.put("sbmc",mBugEquipmentName.getText().toString());
                    updateBug.put("sbxt",mBugEquipmentSystem.getText().toString());
                    updateBug.put("qxmc",mBugName.getText().toString());
                    updateBug.put("fxsj",mFindTime.getText().toString());
                    updateBug.put("qxdj",mBugRecordLevel.getSelectedItem().toString());
                    updateBug.put("qxxx",mBugAppearance.getText().toString());
                    updateBug.put("fxbm",mFindBugDepart.getSelectedItem().toString());
                    updateBug.put("fxr",mFindOwner.getText().toString());
                    updateBug.put("lxr1",mBugFirstLinkName.getText().toString());
                    updateBug.put("lxzy1",mLinkProfession.getSelectedItem().toString());
                    updateBug.put("lxsj1",mLinkTime.getText().toString());
                    updateBug.put("remark",mRemark.getText().toString());
                    updateBug.put("qxxtm",java.util.UUID.randomUUID().toString());
                    updateBug.put("isUpload","0");
                }catch (JSONException e)
                {
                }

                Log.e("=====",updateBug.toString());
                saveBugInLocal(updateBug);
                HttpUtil.requestNetForPostBugRecordData(mYhxtm, mDeviceToken, updateBug, BugRecordActivity.this,"BugRecordActivity");
            }

        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode == KeyEvent.KEYCODE_BACK){

        }

        return super.onKeyDown(keyCode, event);
    }

    public  String getValueByKey(JSONObject jsonObject, String key ){
        String value ;
        try {
            value = (String) jsonObject.get(key);
        } catch (JSONException e) {
            value = "";
            e.printStackTrace();
        }
        return value;
    }
    public void saveBugInLocal(JSONObject updateBug)
    {
        TaskDbHelper taskDbHelper = new TaskDbHelper(BugRecordActivity.this);
        SQLiteDatabase db = taskDbHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            cv.put("user_id",LocalStorage.getUserXtm(BugRecordActivity.this));
            cv.put("data",updateBug.toString());
            cv.put("date",HttpUtil.getCurrentDateString());
            try {
                cv.put("qxxtm",updateBug.getString("qxxtm"));
                cv.put("find_time",updateBug.getString("fxsj"));
            }catch (JSONException e)
            {

            }
            db.insert("bug_list", null, cv);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        db.close();
    }

    public void jumpToBugListActivity()
    {
//        Intent data = new Intent();
//        data.putExtra("uploadData", mUploadData.toString());
//        BugRecordActivity.this.setResult(1002, data);
        BugRecordActivity.this.finish();
    }
    public void uploadBugFailed()
    {
        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(BugRecordActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                jumpToBugListActivity();
            }
        });
    }

    public void uploadBugSuccess(final JSONObject result ,final JSONObject uploadData)
    {
        final Handler mainHander = new Handler(Looper.getMainLooper());
        mainHander.post(new Runnable() {
            @Override
            public void run() {
                try {
                    TaskDbHelper taskDbHelper = new TaskDbHelper(BugRecordActivity.this);
                    SQLiteDatabase db = taskDbHelper.getWritableDatabase();
                    String qxxtm = uploadData.getString("qxxtm");
                    ContentValues cv = new ContentValues();
                    uploadData.put("isUpload","1");
                    cv.put("data",uploadData.toString());
                    int success = db.update("bug_list",cv,"user_id=? and qxxtm=?",new String[]{String.valueOf(LocalStorage.getUserXtm(BugRecordActivity.this)),
                            String.valueOf(qxxtm)});
                    Log.e("success",success+"");
                    db.close();

                    String status = result.getString("status");
                    Toast.makeText(BugRecordActivity.this, "上传"+status, Toast.LENGTH_SHORT).show();
                }catch (JSONException e)
                {

                }
                jumpToBugListActivity();
            }
        });

    }

    public int getPreSelectArrayListIndex(ArrayList list,String name)
    {
        int index = 0;
        for (int i = 0; i < list.size(); i ++)
        {
            if (name.equals(list.get(i)))
            {
                index = i;
            }
        }
        return index;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && resultCode == 1000)
        {
            try {
                JSONObject equipmentInfo = new JSONObject(data.getStringExtra("equipment_code"));
                mBugEquipmentCode.setText(equipmentInfo.getString("equipment_code"));
                mBugEquipmentName.setText(equipmentInfo.getString("equipment_name"));
                mMachineGroup.setSelection(getPreSelectArrayListIndex(getMachineGroupList(),equipmentInfo.getString("jz")));
                mBugEquipmentSystem.setText(equipmentInfo.getString("xt"));
            }catch (JSONException e)
            {

            }

        }
        if (data != null && requestCode == 1001)
        {
            try {
                JSONObject linkerInfo = new JSONObject(data.getStringExtra("linker_name"));
                mBugFirstLinkName.setText(linkerInfo.getString("name"));

            }catch (JSONException e)
            {

            }

        }
    }

    public Spinner initSpinner(String title, Integer id, ArrayList data) {
        final Spinner spinner = (Spinner) findViewById(id);
        spinner.setPrompt(title);
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
        spinner.setAdapter(adapter);
        spinner.setSelection(2);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinner.setSelection(position);
                //todo
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        return spinner;
    }

    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_custom,new LinearLayout(BugRecordActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }
        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("缺陷登记");
        ImageView title_logo = (ImageView)findViewById(R.id.title_logo_id);
        title_logo.setImageResource(R.drawable.quexian_title);
        title_logo.setAlpha(0.7f);
        RelativeLayout bar_back_btn =  (RelativeLayout) findViewById(R.id.bar_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BugRecordActivity.this.finish();
            }
        });
    }


    private ArrayList getDefectLevel() {
        ArrayList list = new ArrayList<String>();
        list.add("一类缺陷");
        list.add("二类缺陷");
        list.add("三类缺陷");
        return list;
    }
    private  ArrayList getMachineGroupList(){
        ArrayList list = new ArrayList<String>();
        list.add("脱硫");
        list.add("网控");
        list.add("燃料");
        list.add("#1机组");
        list.add("厂外");
        list.add("#2机组");
        list.add("公用系统");
        return list;
    }

    private ArrayList getLinkMajorList() {
        ArrayList list = new ArrayList<String>();
        list.add("汽机");
        list.add("电气一次");
        list.add("电气二次");
        list.add("锅炉");
        list.add("热控");
        list.add("燃料");
        list.add("化学");
        list.add("脱硫");
        list.add("脱硝");
        list.add("除灰");
        list.add("信息");

        return list;
    }
    private ArrayList getDepartmentMajorList() {
        ArrayList list = new ArrayList<String>();
        list.add("运行部");
        list.add("公司领导");
        list.add("燃料检验中心");
        list.add("华野检修");
        list.add("龙源环保");
        list.add("泰尔公司");
        list.add("维修部");

        return list;
    }
}
